//
//  search_iPhone_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 24-03-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "search_iPhone_ViewController.h"
#import "classGenericCell.h"
#import "CustomCell.h"
#import "dao.h"

@interface search_iPhone_ViewController ()

@end

@implementation search_iPhone_ViewController

@synthesize objTextSearch;
@synthesize tableViewSearch;
@synthesize dataArraySearch = _dataArraySearch;
@synthesize json;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (IBAction)clearTextSearch:(id)sender{
    
    [objTextSearch becomeFirstResponder]; //Levanta el teclado y pone el foco
    
}

-(void) touchesBegan :(NSSet *) touches withEvent:(UIEvent *)event
{
    [objTextSearch resignFirstResponder]; //Esconde el teclado
    
    UIImage *tabBarBackGroudImage;
    tabBarBackGroudImage = [UIImage imageNamed:@"tab_buscar.png"];
    [self.tabBarController.tabBar setBackgroundImage:tabBarBackGroudImage];

    
    [self.tabBarController.tabBar setHidden:NO];

//  [self showTabBar];
    
    [super touchesBegan:touches withEvent:event ];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [objTextSearch resignFirstResponder];

//Lógica de búsqueda propiamente tal

    NSString *strTitleLabel = @"";
    
    strTitleLabel = objTextSearch.text;
    
    NSLog(@"strTitleLabel = %@", strTitleLabel);
    
    //Almacenamos el registro en una tabla y enviamos a la página siguiente.
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    [prefs setObject:strTitleLabel forKey:@"StringSearch"];
    
    dao *objDAO = [[dao alloc] init];
    [objDAO deleteCurrentProduct];
    
    [objDAO deleteProductBack];
    [objDAO insertProductBack:0];           //Para que vuelva a la busqueda y no al Home
    
    [self performSegueWithIdentifier:@"segueSearchText" sender:nil];
    
    return YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [_dataArraySearch count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:CellIdentifier];
    }
    
    classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
    
//  cell.lblTrademark.text = objCell.strTrademark;

    cell.lblTitleLabel.text = objCell.strTitleLabel;

//  cell.lblIdProducto.text = objCell.strIdProducto;
    
//  cell.lblPrice.text = objCell.strPrice;
//  cell.imgImageView.image = [UIImage imageNamed:@"img_llave.png"];
    
    return cell;
}

- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
    if (range.location != NSNotFound) {
        NSMutableString *mutable = [NSMutableString stringWithString:inputString];
        while (range.location != NSNotFound) {
            [mutable deleteCharactersInRange:range];
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    return inputString;
}

- (void) retrieveDataSearch: (NSString *) stringSearch{
    
    [_dataArraySearch removeAllObjects];
    _dataArraySearch = [[NSMutableArray alloc] init];

    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    
    NSURL * url = [NSURL URLWithString:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonBusquedaProducto.aspx"];
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
    NSString * params =[NSString stringWithFormat:@"strJsonBase=JsonBusquedaPalabras&strBusqueda=%@&strStartIndex=0",  stringSearch];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];//NSNonLossyASCIIStringEncoding  NSUTF8StringEncoding
    
    NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
                                                       completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                           NSLog(@"Response:%@ %@\n", response, error);
                                                           if(error == nil)
                                                           {
                                                               NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                               NSLog(@"Data = %@",text);
                                                               
                                                               //[{"idf":"1", "pal":"Alicate"}, {"idf":"2", "pal":"Alicate universal "}, {"idf":"3", "pal":"Alicate corte "}]
                                                               
                                                               NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                                               newStr = [self stringByRemovingControlCharacters:newStr];
                                                               
                                                               NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
                                                               
                                                               json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
                                                               
                                                               for (int i = 0; i<json.count; i++)
                                                               {
                                                                   //[[json objectAtIndex:i] objectForKey:@"pal"]]
                                                                   
                                                                   NSString *strTitleLabel = [[json objectAtIndex:i] objectForKey:@"pal"];
                                                                   NSString *strSubtitleLabel = @"";
                                                                   NSString *strTrademark = @"";
                                                                   NSString *strIdmark = [NSString stringWithFormat:@"%i", i];
                                                                   
                                                                   NSString *strSKU = @"";
                                                                   NSString *strIdProducto = [NSString stringWithFormat:@"%i" , i];
                                                                   NSString *strReviews = @"";
                                                                   NSString *strPrice = @"";
                                                                   NSString *strOfferPrice = @"";
                                                                   NSString *strPriceDuplicated = @"";
                                                                   NSString *strDiscount = @"";
                                                                   NSString *strOfferTime = @"";
                                                                   NSString *strQty = @"";
                                                                   
                                                                   classGenericCell *objCell = [[classGenericCell alloc] initClassCell:strTitleLabel andSubtitleLabel:strSubtitleLabel andTrademark:strTrademark andIdMark:strIdmark andSKU:strSKU andStrIdProducto:strIdProducto andReviews:strReviews andstrPrice:strPrice andOfferPrice:strOfferPrice andstrPriceDuplicated:strPriceDuplicated andDiscount:strDiscount andOfferTime:strOfferTime andQty:strQty];
                                                                   
                                                                   [_dataArraySearch addObject:objCell];
                                                               }
                                                               
                                                               [self.tableViewSearch reloadData];
                                                               
                                                           }else{
                                                               
                                                               NSLog(@"Nothing was downloaded.");
                                                               NSString *strTitleLabel = @"";
                                                               NSString *strSubtitleLabel = @"";
                                                               NSString *strTrademark = @"";
                                                               NSString *strIdmark = @"";
                                                               
                                                               NSString *strSKU = @"";
                                                               NSString *strIdProducto = @"0";
                                                               NSString *strReviews = @"";
                                                               NSString *strPrice = @"";
                                                               NSString *strOfferPrice = @"";
                                                               NSString *strPriceDuplicated = @"";
                                                               NSString *strDiscount = @"";
                                                               NSString *strOfferTime = @"";
                                                               NSString *strQty = @"";
                                                               
                                                               [_dataArraySearch removeAllObjects];
                                                               _dataArraySearch = [[NSMutableArray alloc] init];
                                                               
                                                               classGenericCell *objCell = [[classGenericCell alloc] initClassCell:strTitleLabel andSubtitleLabel:strSubtitleLabel andTrademark:strTrademark andIdMark:strIdmark andSKU:strSKU andStrIdProducto:strIdProducto andReviews:strReviews andstrPrice:strPrice andOfferPrice:strOfferPrice andstrPriceDuplicated:strPriceDuplicated andDiscount:strDiscount andOfferTime:strOfferTime andQty:strQty];
                                                               
                                                               [_dataArraySearch addObject:objCell];
                                                               
                                                               [self.tableViewSearch reloadData];
                                                           }
                                                       }];
    [dataTask resume];

}

- (IBAction)closeSearch:(id)sender {
    
    [objTextSearch resignFirstResponder];
    
    dao *objDAO = [[dao alloc] init];

    int intIdSearchBack = 0;
    
    intIdSearchBack = [objDAO obtainSearchBack];

    [self.tabBarController.tabBar setHidden:NO];
    [self showTabBar];
    
    if (intIdSearchBack == 1) {

        [objDAO updateSearchBack:0]; //Reseteamos el valor

        [self.tabBarController setSelectedIndex:0]; //Volvemos al home
    }
}

- (IBAction)callNumber:(id)sender {
    
    NSString *strContactPhone;
    
    dao *objDAO = [[dao alloc] init];
    
    strContactPhone = [NSString stringWithFormat:@"tel://%@", [objDAO obtainCallCenterNumber]];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strContactPhone]];
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    self.tableViewSearch.hidden = NO;
    
    NSLog(@"string= %@", string);
    
    NSString *strStringCompuesto = [NSString stringWithFormat:@"%@%@", objTextSearch.text, string];
    
    NSLog(@"strStringCompuesto = %@", strStringCompuesto);
    
    if ((objTextSearch.text.length == 1) && ([string  isEqual: @""])) {
        
        strStringCompuesto = @"";
    }
    
    [self retrieveDataSearch:strStringCompuesto];
    
    return YES;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];

    NSString *strTitleLabel = @"";

    strTitleLabel = objCell.strTitleLabel;
    
    NSLog(@"strTitleLabel = %@", strTitleLabel);

    //Almacenamos el registro en una tabla y enviamos a la página siguiente.
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    [prefs setObject:strTitleLabel forKey:@"StringSearch"];

    dao *objDAO = [[dao alloc] init];
    [objDAO deleteCurrentProduct];
    
    [objDAO deleteProductBack];
    [objDAO insertProductBack:0];           //Para que vuelva a la busqueda y no al Home
    
//    if ([objDAO obtainProductBack] == 0)
    
}

- (void)hideTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds);
                         tabBar.frame = tabFrame;
                         content.frame = window.bounds;
                     }];
}

- (void)showTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds) - CGRectGetHeight(tabBar.frame);
                         tabBar.frame = tabFrame;
                         
                         CGRect contentFrame = content.frame;
                         contentFrame.size.height -= tabFrame.size.height;
                     }];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"iphone_header.png"] forBarMetrics:UIBarMetricsDefault];

//Limpiamos la variable de Id de departamento
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    [prefs setObject:@"0" forKey:@"strIdDepartment"]; //Identifica el Id de departamento si la búsqueda es por este concepto
    
/*
    UIImage *tabBarBackGroudImage;
    tabBarBackGroudImage = [UIImage imageNamed:@"tab_buscar.png"];
    [self.tabBarController.tabBar setBackgroundImage:tabBarBackGroudImage];
*/
    self.tableViewSearch.hidden = YES;
    
    [_dataArraySearch removeAllObjects];
    _dataArraySearch = [[NSMutableArray alloc] init];
    
    if (objTextSearch.text.length > 0) {
        
        self.tableViewSearch.hidden = NO;
        [self retrieveDataSearch:objTextSearch.text];
    }else{

        [self.tableViewSearch reloadData];
        
        [objTextSearch becomeFirstResponder]; //Levanta el teclado y pone el foco
    }

//  [self.tabBarController.tabBar setHidden:NO];
//  [self showTabBar];
    
    self.hidesBottomBarWhenPushed = NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//  [self showTabBar];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
